/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package yandexfotkibackup;

import java.awt.Desktop;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author petr
 */
public class DownloaderThread extends Thread {

    List<PhotoInfo> forDownloading;
    AlbomInfo currentAlbom;
    GuiAlbomsData guiAlbom;

    DownloaderThread(AlbomInfo albom, List<PhotoInfo> forDownloading, GuiAlbomsData guiAlbom) {
        this.forDownloading = forDownloading;
        this.currentAlbom = albom;
        File file = new File(currentAlbom.getTitle());
        file.mkdirs();
        try {
            Desktop.getDesktop().open(file);
        } catch (IOException ex) {
            Logger.getLogger(DownloaderThread.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.guiAlbom = guiAlbom;
    }

    @Override
    public void run() {
        for (int i = 0; i < forDownloading.size(); i++) {
            PhotoInfo photo;
            photo = forDownloading.get(i);
            try {
                String ext = getExt(photo);
                if (ext.equals("jpg")) {
                    ext = "";
                } else {
                    ext = ".jpg";
                }
                String pathname = currentAlbom.getTitle() + File.separator + photo.getName() + ext;
                File photoFile = new File(pathname);
                if(!photoFile.exists()){
                    URL website = new URL(photo.getUrlDownload());
                    ReadableByteChannel rbc = Channels.newChannel(website.openStream());
                    FileOutputStream fos = new FileOutputStream(pathname);
                    fos.getChannel().transferFrom(rbc, 0, 1 << 24);
                    fos.close();
                }
                float v = (float)(i+1)/forDownloading.size();
                guiAlbom.setProgressDownload(v);
            } catch (MalformedURLException ex) {
                Logger.getLogger(ReadXMLDownloadHendler.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(ReadXMLDownloadHendler.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }

    private String getExt(PhotoInfo photo) {
        String ext = "";
        StringTokenizer st = new StringTokenizer(photo.getName(), ".");
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            if (!st.hasMoreTokens() && token.length() <= 4) {
                ext = token;
            }
        }
        return ext.toLowerCase();
    }
}
